<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>宣讲课程</span>
      </div>
    </template>

    <div class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.title" placeholder="标题" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.type" placeholder="课程类型" clearable filterable>
            <el-option v-for="(sItem, sIndex) in courseTypeList" :key="sIndex" :label="sItem.courseTypeName" :value="sItem.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.expertId" placeholder="专家" clearable filterable>
            <el-option v-for="(sItem, sIndex) in expertList" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.isRecommend" placeholder="是否推荐课程" clearable>
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.description" placeholder="课程简介" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.status" placeholder="上下架状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="-1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 18px;">
        <el-button type="primary" @click="upDownMulShelves('up')">批量上架</el-button>
        <el-button type="primary" @click="upDownMulShelves('down')">批量下架</el-button>
        <el-button type="primary" @click="addCourse">新建</el-button>
      </div>
    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="courseData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
        ref="courseTableRef"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(tableItem, tableIndex) in courseTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          :show-overflow-tooltip="tableItem.field != 'coverUrl'"
        >
          <template #default="scope" v-if="tableItem.slot">
            <slot :name="tableItem.slot" v-bind="scope">
              <el-image class="table-item-img" :src="reFileResult(scope.row.coverUrl)" fit="cover">
                <template #error>
                  <div class="image-slot">
                    <el-image style="width: 200px;" src="/images/course_default.png" fit="cover" />
                  </div>
                </template>
              </el-image>
            </slot>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="150"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              v-if="row.status != 1"
              @click="upDownShelves('up', row)"
            >上架</el-button>
            <el-button
              type="warning"
              link
              v-if="row.status == 1"
              @click="upDownShelves('down', row)"
            >下架</el-button>
            <el-button
              type="warning"
              link
              @click="courseDetail(row)"
            >查看</el-button>
            <el-button
              type="success"
              link
              @click="courseEdit(row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>
  </el-card>
</template>
<script>
export default { name: 'backendPublicizeCourse' }
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/http/index';
import { dateFormatter, checkStatusFormatter, reFileResult } from "@/utils/backend.js"
import { ContentTypeEnum } from '@/enums/httpEnum';
import { useAuthStore } from '@/stores/modules/auth.js';

/* 路由 */
const route = useRouter();

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  getCourseTypeList()
  getExpertList()
  onSubmit()
})

/* 课程类型下拉列表请求 */
const courseTypeList = ref([])
const coursePageIndex = ref(1)
const coursePageType = ref(200)

const getCourseTypeList = () => {
  let params = {
    pageIndex: coursePageIndex.value,
    pageSize: coursePageType.value
  }
  http.$POST(`/PreachM/GetPreachCourseTypeInfoList`, params).then(res => {
    courseTypeList.value = courseTypeList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      coursePageIndex.value = coursePageIndex.value + 1
      getCourseTypeList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 专家下拉列表请求 */
const expertList = ref([])
const expertPageIndex = ref(1)
const expertPageSize = ref(1000)
const getExpertList = () => {
  let params = {
    pageIndex: expertPageIndex.value,
    pageSize: expertPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetExpertInfoList`, params).then(res => {
    expertList.value = expertList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      expertPageIndex.value = expertPageIndex.value + 1
      getExpertList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 搜索表单 */
const formInline = ref({
  title: "",
  type: "",
  expertId: "",
  isRecommend: "",
  description: "",
  status: "",
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

if(route.currentRoute.value.query.currentPage) {
  currentPage.value = Number(route.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格 */
const courseTableRef = ref(null)

/* 表格数据 */
const courseData = ref([])

/* 是否推荐字段过滤数值 */
const isRecommendFormatter = (row, column, cellValue) => {
  return cellValue == 0 ? '否' : '是'
}

/* 课程类型字段过滤数值 */
const courseTypeFormatter = (row, column, cellValue) => {
  let find = courseTypeList.value.find(item => item.id == cellValue)
  if (find) {
    return find.courseTypeName
  } else {
    return ""
  }
}

/* 上下架状态字段过滤数值 */
const statusFormatter = (row, column, cellValue) => {
  return cellValue == 1 ? '上架' : cellValue == -1 ? '下架' : ''
}

/* 表格字段 */
const courseTableColumns = reactive([
  { field: "title", label: "标题", minWidth: "180" },
  { field: "type", label: "课程类型", minWidth: "120", formatter: courseTypeFormatter },
  { field: "minute", label: "课程时长/分钟", minWidth: "120" },
  { field: "expertName", label: "专家", minWidth: "120" },
  /* { field: "pubUnit", label: "发布单位", minWidth: "150" }, */
  { field: "coverUrl", label: "课程封面", minWidth: "250", slot: "imgView" },
  { field: "joinPeopleCount", label: "参与人次", minWidth: "120" },
  { field: "isRecommend", label: "是否推荐", minWidth: "120", formatter: isRecommendFormatter },
  { field: "status", label: "上下架状态", minWidth: "120", formatter: statusFormatter },
  { field: "mark", label: "评分", minWidth: "120" },
])

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  let dfi = {
    Logic: 0,
    Filters: []
  }
  
  for (let k in formInline.value){
    if(formInline.value[k] !== ""){
      if(k == "title" || k == "description") {
        dfi.Filters.push({
          Field: k,
          Operator: 0,
          Value: formInline.value[k]
        })
      }else {
        dfi.Filters.push({
          Field: k,
          Operator: 8,
          Value: formInline.value[k]
        })
      }
    }
  }

  if(dfi.Filters.length){
    params.dfi = dfi
  }
  http.$POST("/PreachM/GetPreachCourseInfoList", params).then(res => {
    loading.value = false
    if (res.isError) return
    courseData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 点击新建 */
const addCourse = () => {
  route.push({
    path: "/backend/publicize-course/add",
    query: { type: 'add' }
  })
}

/* 点击编辑 */
const courseEdit = (row) => {
  route.push({
    path: "/backend/publicize-course/add",
    query: { id: row.id, type: 'edit', currentPage: currentPage.value }
  })
}

/* 点击查看详情 */
const courseDetail = (row) => {
  let { href } = route.resolve({
    path: "/backend/publicize-course/detail",
    query: { id: row.id, currentPage: currentPage.value }
  })
  window.open(href, "_blank")
}

/* 点击上、下架 */
const upDownShelves = (type, row) => {
  let params = {
    id: row.id,
    status: ""
  }
  if(type == 'up') {
    params.status = 1
  } else {
    params.status = -1
  }
  http.$POST("/PreachM/AddOrUpdatePreachCourseInfo", {...params}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA} }).then(res => {
    if(res.IsError) {
      ElMessage.warning('操作失败');
    }else{
      ElMessage.success('操作成功');
      onSubmit()
    }
  }).catch(err => {
    ElMessage.warning('操作失败');
  })
}

/* 点击批量上、下架 */
const upDownMulShelves = (type) => {
  let checkList = courseTableRef.value.getSelectionRows()
  if(!checkList.length) {
    ElMessage.warning("请先选择要进行操作的数据")
    return 
  }
  let params = []
  checkList.forEach((item) => {
    if(type == "up") {
      params.push({
        id: item.id,
        authToken: authStore.auth_token,
        status: 1
      })
    } else {
      params.push({
        id: item.id,
        authToken: authStore.auth_token,
        status: -1
      })
    }
  })

  http.$POST("/PreachM/UpdatePreachCourseStatus", params).then(res => {
    if(res.IsError) {
      ElMessage.warning('操作失败');
    }else{
      ElMessage.success('操作成功');
      courseTableRef.value.clearSelection()
      onSubmit()
    }
  }).catch(err => {
    ElMessage.warning('操作失败');
  })
}

</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
:deep(.search-form .el-input){
  width: 150px !important;
}
</style>